﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using GNSCore.Model.Context;
using GNSCore.Repositories;

namespace GNSCore.Repositories
{
    /// <summary>
    /// Base repository, contains implementation
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Repository<T> : IRepository<T>
    {
        private IGNSContext _context;

        #region IRepository<T> Members

        /// <summary>
        /// Sets current data context to the repository
        /// </summary>
        /// <param name="context">Data context</param>
        public void SetContext(IGNSContext context)
        {
            _context = context;
        }

        /// <summary>
        /// Returns all items of type T
        /// </summary>
        /// <returns>Items</returns>
        public IQueryable<T> GetAll<T>()
        {
            return _context.CreateQuery<T>();
        }

        /// <summary>
        /// Returns item by it's id
        /// </summary>
        /// <param name="Id">Item identifier</param>
        /// <returns>Item of type T</returns>
        public T GetById(int Id)
        {
            throw new NotImplementedException();
            //return (T)_context.GetObjectByKey(new EntityKey("Id","Id",Id));
        }

        /// <summary>
        /// Saves item changes
        /// </summary>
        /// <param name="item">Item to save</param>
        public void Save(T item)
        {
            _context.ApplyPropertyChanges(item.GetType().Name, item);
        }

        /// <summary>
        /// Saves new item
        /// </summary>
        /// <param name="item">Item to save</param>
        public void Add(T item)
        {
            _context.AddObject(item.GetType().Name, item);
        }

        /// <summary>
        /// Remove by id
        /// </summary>
        /// <param name="Id">Entity identifier</param>
        public void RemoveById(int Id)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Removes entity 
        /// </summary>
        /// <param name="item"></param>
        public void Remove(T item)
        {
            _context.DeleteObject(item);
        }

        /// <summary>
        /// Saves context to the data base
        /// </summary>
        /// <param name="acceptchanges">Accept changes, during saving</param>
        /// <returns>Detepmines, whether saving was success</returns>
        public int SaveChanges(bool acceptchanges)
        {
            return _context.SaveChanges(acceptchanges);
        }

        #endregion
    }
}